package systems.particles 
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.geom.Point;
	import flash.geom.Vector3D;
	
	/**
	 * ...
	 * @author Nicolas Barradeau
	 * http://en.nicoptere.net
	 */
	public class Viewport extends Sprite
	{
		
		
		
		protected var bmp:Bitmap;
		protected var bd:BitmapData;
		private var _bgColor:uint;
		
		private var _screenWidth:int = 1;
		private var _screenHeight:int = 1;
		
		private var projection:Vector.<Number>;
		
		public function Viewport( width:int = 500, height:int = 500, bgColor:uint = 0xFF000000 ) 
		{
			
			_bgColor = bgColor;
			
			bd = new BitmapData( width, height, true, _bgColor );
			bmp = new Bitmap( bd, 'auto', false );
			addChild( bmp );
			
			screenWidth = width;
			screenHeight = height;
			
		}
		
		public function renderVectors( vectors:Vector.<Vector3D> ):void
		{
			
			draw( Renderer3D.projectVectors( vectors ), vectors );
			
		}
		
		public function render( vertices:Vector.<Number>, vectors:Vector.<Vector3D> ):void
		{
			draw( Renderer3D.project( vertices, new Point( screenWidth / 2, screenHeight / 2), false ), vectors );
		}
		
		private function draw( projection:Vector.<Number>, vectors:Vector.<Vector3D> ):void
		{
			
			bd.fillRect( bd.rect, bgColor );
				
			var i:int, j:int, count:int, _x:int, _y:int, _z:int, _t:int = 0, cx:int, cy:int;
			var z:Number;
			var v:Vector3D;
			var offx:Number, offy:Number;
			
			cx = screenWidth / 2;
			cy = screenHeight / 2;
			
			count = projection.length;
			for ( i = 0 ; i < count; i += 2 )
			{
				_x = cx + projection[ i ];
				_y = cy + projection[ i + 1 ];
				
				v = vectors[ int( i / 2 ) ];
				bd.setPixel32( _x, _y, 0xFF << 24 | ( v.x + 0x80 ) << 16 | ( v.y + 0x80 )  << 8 | ( v.z + 0x80 ) );
				
				/*
				j = int( i * 1.5 ) + 2;
				z = 1 - ( Renderer3D.uvt[ j ] - Renderer3D.minZ ) / Renderer3D.maxZ;
				bd.setPixel32(  _x, _y, 0xFF - ( z * 0xFF ) << 24 | v.x << 16 | v.y << 8 | v.z );
				*/
				
				/*
				if( _t == 0 )
				{
				}
				else
				{
					//_t = pool.textures[ int( i / 2 ) ];
					rect = rects[ _t ];
					offx = rect.width / 2;
					offy = rect.height / 2;
					rect.x = int( z * depths[ _t ] ) * rect.width;
					bd.copyPixels( maps[ _t ], rect, new Point( _x - offx, _y - offy ), null, null, true );
				}
				*/
			}
		}
		
		public function get bgColor():uint { return _bgColor; }
		
		public function set bgColor(value:uint):void 
		{
			_bgColor = value;
		}
		
		public function get screenWidth():int { return _screenWidth; }
		
		public function set screenWidth(value:int):void 
		{
			_screenWidth = value;
		}
		
		public function get screenHeight():int { return _screenHeight; }
		
		public function set screenHeight(value:int):void 
		{
			_screenHeight = value;
		}
	}

}